package test.niit.edu.cn.android1920;

import android.database.SQLException;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    StudentOP studentOP;
    ListView listView;
    EditText edt_name;
    Button btn_add,btn_delet;
    ArrayAdapter<Object> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.list);
        edt_name = (EditText)findViewById(R.id.edit_name);
        btn_add = (Button)findViewById(R.id.addBtn);
        btn_delet = (Button)findViewById(R.id.deleteBtn);
        studentOP = new StudentOP(this);
        try{
            studentOP.open();
        }catch (SQLException e){
            e.printStackTrace();
        }
        ArrayList<Object> values = studentOP.getStuInfo();
        adapter = new ArrayAdapter<Object>(this,android.R.layout.simple_list_item_1,values);
        listView.setAdapter(adapter);

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String stuName = edt_name.getText().toString();
                if(stuName.equals("")){
                    Toast.makeText(MainActivity.this,"姓名不能为空！",Toast.LENGTH_LONG).show();
                    return;
                }
                StudentBean stud = studentOP.addStudent(stuName);
                adapter.add(stud);
                edt_name.setText("");
            }
        });
        btn_delet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(adapter.getCount()>0){
                    StudentBean stud = (StudentBean)adapter.getItem(0);
                    studentOP.deleteStudent(stud);
                    adapter.remove(stud);
                }
            }
        });


    }
}
